package com.epro.dx.adapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

public class IdentitiesAdapter extends PagerAdapter {

	private Context mContext;
	private int[] imgIDs;
	private List<ImageView> imageViews = new ArrayList<ImageView>();

	/**
	 * @param mContext
	 *            上下文
	 * @param imgIds
	 *            要展示的图片id数组
	 */
	public IdentitiesAdapter(Context mContext, int[] imgIDs) {
		this.mContext = mContext;
		this.imgIDs = imgIDs;
	}

	@Override
	public int getCount() {
		if (imgIDs != null)
			return imgIDs.length;
		return 0;
	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		container.removeView((View) object);
	}

	@Override
	public Object instantiateItem(ViewGroup container, int position) {
		ImageView image = null;
		if (imageViews.size() > position) {
			image = imageViews.get(position);
		}
		if (null == image) {
			image = new ImageView(mContext);
			image.setScaleType(ScaleType.FIT_XY);
			image.setImageResource(imgIDs[position]);
			imageViews.add(image);
		}
		container.addView(image);
		return image;
	}

	@Override
	public boolean isViewFromObject(View view, Object object) {
		return view == object;
	}

	/**
	 * 回收图片
	 */
	public void reclyImage() {
		for (int i = 0; i < imageViews.size(); i++) {
			ImageView image = imageViews.get(i);
			if (null == image) {
				return;
			}
			image.setImageBitmap(null);
			Drawable drawn = image.getDrawable();
			if (drawn instanceof BitmapDrawable) {
				BitmapDrawable tmpBitMap = ((BitmapDrawable) drawn);

				if (null != tmpBitMap.getBitmap()) {
					Bitmap bitMap = tmpBitMap.getBitmap();
					if (null != bitMap && !bitMap.isRecycled()) {
						bitMap.recycle();
					}
				}
			}
		}
		imageViews.clear();

	}

}
